package com.bhs.sansonglogistics.ui.wallet;

import static com.shouzhong.scanner.Result.TYPE_ID_CARD_FRONT;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.GlideEngine;
import com.bhs.sansonglogistics.bean.BusinessInfo;
import com.bhs.sansonglogistics.bean.CompanyBean;
import com.bhs.sansonglogistics.bean.IdentityBean;
import com.bhs.sansonglogistics.bean.ImageReturn;
import com.bhs.sansonglogistics.dialog.BottomSelectDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.enterprise.EnterpriseCertificationActivity;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.shouzhong.scanner.Result;
import com.shouzhong.scanner.ScannerUtils;

import java.util.ArrayList;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 增加企业账户
 */
public class AddBusinessAccountActivity extends BaseActivity implements View.OnClickListener, NetCallBack, TextWatcher {

    private ImageView mIvBusinessLicense;
    private EditText mTvCompanyName;
    private EditText mTvSocialCreditCode;
    private EditText mTvAddress;

    private ImageView mIvFront;

    private ImageView mIvReverseSide;
    private EditText mTvName;
    private EditText mTvIdNumber;
    private EditText mEtPrincipal;
    private Button mBtnSubmit;
    private int type;
    private String company_lisence_pic, legal_card_front, legal_card_back;
    private BusinessInfo businessInfo=new BusinessInfo();
    @Override
    public int initLayout() {
        return R.layout.activity_add_business_account;
    }

    @Override
    public void initView() {

        TextView mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText("增加企业账户");
        RelativeLayout mRlBusinessLicense = findViewById(R.id.rl_business_license);
        mRlBusinessLicense.setOnClickListener(this);
        mIvBusinessLicense = findViewById(R.id.iv_business_license);
        mTvCompanyName = findViewById(R.id.tv_company_name);
        mTvSocialCreditCode = findViewById(R.id.tv_social_credit_code);
        mTvAddress = findViewById(R.id.tv_address);
        RelativeLayout mRlFront = findViewById(R.id.rl_front);
        mRlFront.setOnClickListener(this);
        mIvFront = findViewById(R.id.iv_front);
        RelativeLayout mRlReverseSide = findViewById(R.id.rl_reverse_side);
        mRlReverseSide.setOnClickListener(this);
        mIvReverseSide = findViewById(R.id.iv_reverse_side);
        mTvName = findViewById(R.id.tv_name);
        mTvIdNumber = findViewById(R.id.tv_id_number);
        mEtPrincipal = findViewById(R.id.et_principal);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mBtnSubmit.setOnClickListener(this);

        mTvCompanyName.addTextChangedListener(this);
        mTvSocialCreditCode.addTextChangedListener(this);
        mTvAddress.addTextChangedListener(this);
        mTvName.addTextChangedListener(this);
        mTvIdNumber.addTextChangedListener(this);
        mEtPrincipal.addTextChangedListener(this);
    }

    @Override
    public void initData() {

    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_business_license:
                type = 1;
                bottomSelect();
                break;
            case R.id.rl_front:
                type = 2;
                bottomSelect();
                break;
            case R.id.rl_reverse_side:
                type = 3;
                bottomSelect();
                break;
            case R.id.btn_submit:
                businessInfo.company_address=mTvAddress.getText().toString();
                businessInfo.company_lisence_no=mTvSocialCreditCode.getText().toString();
                businessInfo.company_name=mTvCompanyName.getText().toString();
                businessInfo.legal_truename=mTvName.getText().toString();
                businessInfo.legal_card_no=mTvIdNumber.getText().toString();
                businessInfo.legal_mobile=mEtPrincipal.getText().toString();
                startActivity(new Intent(mActivity, AddCardActivity.class)
                        .putExtra("bank_type",2)
                        .putExtra("info",businessInfo));
                break;
        }
    }


    private BasePopupView basePopupView;
    private BottomSelectDialog bottomSelectDialog;

    private void bottomSelect() {
        if (basePopupView == null) {
            bottomSelectDialog = new BottomSelectDialog(this);
            bottomSelectDialog.setMyClickListener(new MyClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getId() == R.id.tv_take_picture) {
                        photograph();
                    } else if (v.getId() == R.id.tv_photo_album) {
                        photoAlbum();
                    }
                    basePopupView.dismiss();
                }
            });
            basePopupView = new XPopup.Builder(mActivity)
                    .asCustom(bottomSelectDialog)
                    .show();
        } else {
            basePopupView.show();
        }
    }

    private void photograph() {
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofImage())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        getIdentityInformation(result.get(0).getRealPath());
                        MyUtils.imageUpload(mActivity, result, AddBusinessAccountActivity.this, 9527);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    private void getIdentityInformation(String path) {
        if (type == 2) {
            Glide.with(mContext).load(path).into(mIvFront);
            Result result = null;
            try {
                result = ScannerUtils.decodeIdCard(mActivity, MyUtils.openImage(path));
                if (result.type == TYPE_ID_CARD_FRONT) {
                    IdentityBean identityBean = new Gson().fromJson(result.data, IdentityBean.class);
                    mTvName.setText(identityBean.getName());
                    mTvIdNumber.setText(identityBean.getCardNumber());
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (type == 3) {
            Glide.with(mContext).load(path).into(mIvReverseSide);
        }
    }

    private void photoAlbum() {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setMaxSelectNum(1)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        getIdentityInformation(result.get(0).getRealPath());
                        MyUtils.imageUpload(mActivity, result, AddBusinessAccountActivity.this, 9527);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        //上传照片
        if (requestCode == 9527) {
            loadingPopupDismiss();
            ImageReturn dataBean = new Gson().fromJson(json, ImageReturn.class);
            if (dataBean.isStatus()) {
                if (type == 1) {
                    company_lisence_pic = dataBean.getData().getSrc();
                    businessInfo.company_lisence_pic=company_lisence_pic;
                    Glide.with(mContext).load(company_lisence_pic).into(mIvBusinessLicense);
                    networkRequest(netApi.identifyBusinessLicense(company_lisence_pic), AddBusinessAccountActivity.this, 9528);
                } else if (type == 2) {
                    legal_card_front = dataBean.getData().getSrc();
                    businessInfo.legal_card_front=legal_card_front;
                } else if (type == 3) {
                    legal_card_back = dataBean.getData().getSrc();
                    businessInfo.legal_card_back=legal_card_back;
                }
                verify();
            } else {
                ToastUtil.show(dataBean.getMsg());
            }

        } else if (requestCode == 9528) {
            //图片识别
            loadingPopupDismiss();
            CompanyBean dataBean = new Gson().fromJson(json, CompanyBean.class);
            if (dataBean.isStatus()) {
                mTvSocialCreditCode.setTag(dataBean.getData().getLicense_info().getLicense_no());
                mTvCompanyName.setText(dataBean.getData().getLicense_info().getCompany_name());
                mTvAddress.setText(dataBean.getData().getLicense_info().getAddress());
            } else {
                ToastUtil.show("图片识别失败，请重新上传");
            }

        }
    }

    private void verify() {
        boolean verify = !TextUtils.isEmpty(company_lisence_pic) && !TextUtils.isEmpty(legal_card_back) && !TextUtils.isEmpty(legal_card_front);
        if (TextUtils.isEmpty(mTvCompanyName.getText()) || TextUtils.isEmpty(mTvSocialCreditCode.getText()) || TextUtils.isEmpty(mTvAddress.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mTvName.getText()) || TextUtils.isEmpty(mTvIdNumber.getText()) || TextUtils.isEmpty(mEtPrincipal.getText())) {
            verify = false;
        }

        mBtnSubmit.setEnabled(verify);
        mBtnSubmit.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }

    @Override
    public void onFailure(int requestCode) {

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        verify();
    }
}